package com.cjy.expenses.extra;

import com.base.common.datesource.MultipleDataSource;
import com.base.common.enums.PayStatus;
import com.base.common.enums.PayWays;
import com.base.common.json.JsonUtil;
import com.base.common.persistent.dao.*;
import com.base.common.persistent.model.*;
import com.base.common.persistent.query.TNewsQuery;
import com.base.common.utils.EasyUtil;
import com.base.common.webservice.entity.HZService.HZServiceArgs;
import com.base.common.webservice.entity.HZService.UserRevTradingByCstIDBean;
import com.base.common.webservice.entity.SYS86Service.PayFee;
import com.base.common.webservice.entity.SYS86Service.PayFeeInfo;
import com.base.common.webservice.entity.SYS86Service.UserRevPayFeeBean;
import com.base.common.webservice.util.HZServiceUtil;
import com.base.common.webservice.util.SYS86ServiceUtil;
import com.cjy.payment.alipay.entity.AlipayNotifyEntity;
import com.cjy.payment.unionpay.acp.entity.UnionpayNotifyEntity;
import com.cjy.payment.weixin.bean.WeixinNotifyEntity;
import org.apache.commons.lang.text.StrBuilder;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class DoFee {

    private TransactionDetailMapper transactionDetailMapper;

    private TransactionMapper transactionMapper;

    private UserMapper userMapper;

    private VillageConfigMapper villageConfigMapper;

    private ShopOrderMapper shopOrderMapper;

    private ShopUserMapper shopUserMapper;

    private ShopOrderItemMapper shopOrderItemMapper;

    private CompoundsMapper compoundsMapper;

    private TNewsMapper tNewsMapper;

    private CompoundsShopMapper compoundsShopMapper;

    private TShopsMapper tShopsMapper;

    private EasyUtil easyUtil;

    @Transactional
    public void doFeeI(AlipayNotifyEntity alipayNotifyEntity) {
        updateTransaction(alipayNotifyEntity.getOut_trade_no(), PayWays.ALIPAY.getValue());
    }

    @Transactional
    public void doFeeW(WeixinNotifyEntity weixinNotifyEntity) {
        updateTransaction(weixinNotifyEntity.getOut_trade_no(), PayWays.WEIXIN.getValue());
    }

    public void doFeeU(UnionpayNotifyEntity unionpayNotifyEntity) {

        updateTransaction(unionpayNotifyEntity.getOrderId(), PayWays.YINLIAN.getValue());
    }

    @Transactional
    private void updateTransaction(String getOut_trade_no, int payWay) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "spring.xml", "spring-mybatis.xml");
        // an ApplicationContext is also a BeanFactory (via inheritance)
        BeanFactory factory = context;

        transactionDetailMapper = factory.getBean(TransactionDetailMapper.class);
        transactionMapper = factory.getBean(TransactionMapper.class);
        userMapper = factory.getBean(UserMapper.class);
        villageConfigMapper = factory.getBean(VillageConfigMapper.class);
        shopOrderMapper = factory.getBean(ShopOrderMapper.class);
        compoundsMapper = factory.getBean(CompoundsMapper.class);
        shopUserMapper = factory.getBean(ShopUserMapper.class);
        shopOrderItemMapper = factory.getBean(ShopOrderItemMapper.class);
        tNewsMapper = factory.getBean(TNewsMapper.class);
        compoundsShopMapper = factory.getBean(CompoundsShopMapper.class);
        tShopsMapper = factory.getBean(TShopsMapper.class);
        easyUtil = factory.getBean(EasyUtil.class);

        Transaction transaction = transactionMapper.queryByOut_trade_no(getOut_trade_no);
        if (transaction == null || transaction.getId() == 0) {
            ShopOrder shopOrder = new ShopOrder();
            shopOrder.setOutTradeNo(getOut_trade_no);
            shopOrder.setStatus(PayStatus.SUCCESS.getValue());
            System.out.println(shopOrderMapper.updateByOutTradeNo(shopOrder));
            ShopOrder order = shopOrderMapper.selectByCondition(shopOrder).get(0);
            ShopOrderItem shopOrderItem = new ShopOrderItem();
            shopOrderItem.setOrderId(order.getId());
            StrBuilder strBuilder = new StrBuilder();
            List<ShopOrderItem> shopOrderItems = shopOrderItemMapper.selectByCondition(shopOrderItem);
            int rid = shopOrderItems.get(0).getRid();
            shopOrderItems.forEach((item)->{
                strBuilder.append(item.getName() + "\t购买数量：" + item.getNum() + "\n");
            });
            MultipleDataSource.setDataSourceKey("shopDataSource");
            int ctypeB = tNewsMapper.selectByPrimaryKey(rid).getCtypeB();
            String uname = tShopsMapper.selectByPrimaryKey((long) ctypeB).getcUname();
            MultipleDataSource.setDataSourceKey("sqlserverDataSource");

            Double scoreProportionByShopID = 0.00;

            scoreProportionByShopID = compoundsShopMapper.getScoreProportionByShopID(ctypeB);
            easyUtil.sendSms("您有新的订单\n订单号为：" + order.getOutTradeNo()
                    + "\n金额为：" + (order.getFee()/100) + "元"
                    + "\n收货人姓名：" + order.getUsername()
                    + "\n收货人电话：" + order.getPhone()
                    + "\n地址：" + order.getAddress()
                    + "\n所购商品："
                    + "\n" + strBuilder.toString(), uname);

            int score = order.getFee() >= 1000 ? (int)((order.getFee() / 100) * scoreProportionByShopID) : 0;
            ShopUser shopUser = new ShopUser();
            shopUser.setTerminalCode(order.getTerminalCode());
            List<ShopUser> shopUsers = new ArrayList<>();
            shopUsers = shopUserMapper.selectByCondition(shopUser);
            shopUser = shopUsers.get(0);
            shopUser.setScore(score + shopUser.getScore());
            shopUserMapper.updateByPrimaryKeySelective(shopUser);

        } else if (transaction.getStatus() == PayStatus.WAITING.getValue()) {
            Transaction tran = new Transaction();
            tran.setStatus(PayStatus.SUCCESS.getValue());
            tran.setGmt_payment(new Date());
            tran.setOut_trade_no(transaction.getOut_trade_no());
            tran.setPayWay(payWay);
            transactionMapper.updateTransaction(tran);
            String ways = "";
            switch (payWay) {
                case 0:
                    ways = "支付宝";
                    break;
                case 1:
                    ways = "微信";
                    break;
                case 2:
                    ways = "银联";
                    break;
                default:
                    break;
            }

            List<User> users = userMapper.queryUserById(transaction.getUser_id());
            List<TransactionDetail> transactionDetails = transactionDetailMapper.queryTransactionDetailByTransactionId(transaction.getId());
            for (TransactionDetail transactionDetail : transactionDetails) {
                // 开启思源数据提交重复线程
                String finalWays = ways;
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        boolean is_success = true;
                        while (is_success) {
                            DecimalFormat decimalFormat = new DecimalFormat("#00");
                            System.out.println("支付方式：" + finalWays);
                            if (compoundsMapper.queryCompoundsById(users.get(0).getCompounds().getId()).get(0).getCompany().getId() == 5){
                                final String[] tradingID = {""};
                                List<UserRevTradingByCstIDBean> userRevTradingByCstIDBeans = HZServiceUtil.getUserRevTradingByCstID(transactionDetail.getCusID());
                                for (UserRevTradingByCstIDBean userRevTradingByCstIDBean : userRevTradingByCstIDBeans) {
                                    if (finalWays.equals(userRevTradingByCstIDBean.getNames().trim())) {
                                        System.out.println("支付ID" + userRevTradingByCstIDBean.getID());
                                        tradingID[0] = userRevTradingByCstIDBean.getID();
                                    }
                                }
                                /*userRevTradingByCstIDBeans.stream().forEach((item) -> {

                                });*/
                                System.out.println("支付ID" + tradingID[0]);
                                int result = HZServiceUtil.addUserRevPayFeeByBank(transactionDetail.getRevFeeId(), (((double) transactionDetail.getFee()) / 100), tradingID[0], finalWays, new SimpleDateFormat("yyyy-MM-dd").format(new Date()), villageConfigMapper.getProjectID(users.get(0).getCompounds().getId()));
                                //System.out.println(transactionDetail.getRevFeeId() + "," + (((double) transactionDetail.getFee()) / 100) + "," + finalWays + "," + transaction.getOut_trade_no() + "," + villageConfigMapper.getProjectID(users.get(0).getCompounds().getId()));
                                //System.out.println("汇众思源缴费结果：" + result);
                                if (result == 1) {
                                    TransactionDetail detail = new TransactionDetail();
                                    detail.setId(transactionDetail.getId());
                                    detail.setIs_sync(1);
                                    transactionDetailMapper.updateTransactionDetail(detail);
                                    is_success = false;
                                } else {
                                    try {
                                        Thread.sleep(3000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            } else {
                                PayFeeInfo payFeeInfo = new PayFeeInfo();
                                List<PayFee> fees = new ArrayList<PayFee>();
                                PayFee fee = new PayFee();
                                fee.setRevID(transactionDetail.getRevFeeId());
                                fee.setBillNo(transaction.getOut_trade_no());

                                String money = decimalFormat.format(((double) transactionDetail.getFee()) / 100);
                                fee.setRevMoney(money);
                                fees.add(fee);
                                payFeeInfo.setSyswin(fees);
                                String payFeeInfoStr = JsonUtil.dto2String(payFeeInfo);
                                UserRevPayFeeBean payFeeBean = SYS86ServiceUtil.UserRev_PayFee(transactionDetail.getCusID(), villageConfigMapper.getProjectID(users.get(0).getCompounds().getId()), null, finalWays, finalWays, payFeeInfoStr);
                                if ("1".equals(payFeeBean.getState())) {
                                    TransactionDetail detail = new TransactionDetail();
                                    detail.setId(transactionDetail.getId());
                                    detail.setIs_sync(1);
                                    transactionDetailMapper.updateTransactionDetail(detail);
                                    is_success = false;
                                } else {
                                    try {
                                        Thread.sleep(3000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }

                        }
                    }
                });
                thread.start();
            }
        }
    }

}
